#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QPixmap>
#include <QPalette>

loginWindow::loginWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::loginWindow)
{
    ui->setupUi(this);

    // --- 设置界面背景和标题 ---
    QPixmap pixmap("../../../resource/1.jpg");
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);
    this->setPalette(palette);
    this->setWindowTitle("医生端");

    // --- 初始化网络连接 ---
    clientSocket = new QTcpSocket(this); // 传入this，方便Qt自动管理内存

    // --- 绑定信号与槽 ---
    // 这是Qt网络编程的核心，使用异步非阻塞的方式处理网络事件
    connect(clientSocket, &QTcpSocket::connected, this, &loginWindow::onConnected);
    connect(clientSocket, &QTcpSocket::disconnected, this, &loginWindow::onDisconnected);
    connect(clientSocket, &QAbstractSocket::errorOccurred, this, &loginWindow::displayError);
    connect(clientSocket, &QTcpSocket::readyRead, this, &loginWindow::onReadyRead); // 新增：数据到达时触发

    // 禁用登录按钮，直到成功连接服务器
    ui->LoginButton->setEnabled(false);


    // --- 尝试连接服务器 ---
    qDebug() << "Attempting to connect to server...";
    clientSocket->connectToHost("101.43.50.74", 8081); // 使用异步方式连接

    // 创建其他窗口实例，但不立即显示
    selectWindowPtr = new SelectWindow(clientSocket);
}

loginWindow::~loginWindow()
{
    delete ui;
    // clientSocket由于父对象是this，会被自动析构
}

// --- 网络事件处理槽函数 ---

void loginWindow::onConnected()
{
    qDebug() << "Connected to server successfully!";
    ui->LoginButton->setEnabled(true); // 连接成功，启用登录按钮
}

void loginWindow::onDisconnected()
{
    qDebug() << "Disconnected from server.";
    ui->LoginButton->setEnabled(false); // 连接断开，禁用登录按钮
    QMessageBox::warning(this, "连接断开", "与服务器的连接已断开。");
}

void loginWindow::displayError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError); // 避免编译器关于未使用参数的警告
    QString errorMsg = clientSocket->errorString();
    qDebug() << "Connection error:" << errorMsg;
    QMessageBox::critical(this, "网络错误", "无法连接到服务器: " + errorMsg);
}

// --- 按钮点击和窗口管理 ---

void loginWindow::on_LoginButton_clicked()
{
    // 再次检查连接状态，以防万一
    if (clientSocket->state() != QAbstractSocket::ConnectedState) {
        QMessageBox::warning(this, "提示", "尚未连接到服务器，正在尝试重连...");
        clientSocket->connectToHost("101.43.50.74", 8081); // 尝试重连
        return;
    }

    QString username = ui->UserNameEdit->text();
    QString password = ui->PassWordEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "提示", "用户名和密码不能为空！");
        return;
    }

    QString queryStr = "SELECT * FROM Doctors WHERE username = '" + username + "' AND password = '" + password + "';";
    qDebug() << "Sending login query:" << queryStr;

    clientSocket->write(queryStr.toUtf8());
    // 注意：不再使用 waitForReadyRead，而是通过 onReadyRead 信号槽来接收数据
}

// loginwindow.cpp
void loginWindow::onReadyRead()
{
    qDebug() << "Data received in loginWindow.";
    QByteArray data = clientSocket->readAll();
    QString receivedData = QString::fromUtf8(data).trimmed();

    if (receivedData.isEmpty()) return;

    // 关键：检查响应是否包含用户名，以此判断是否为登录响应
    // 这是一个临时的、不严谨的判断方法
    QString currentUsernameInUI = ui->UserNameEdit->text();
    if (!receivedData.contains(currentUsernameInUI) && receivedData != "failed") {
        qDebug() << "Ignoring irrelevant data:" << receivedData;
        return; // 如果收到的数据和登录无关，直接忽略
    }

    if (receivedData == "failed") {
        QMessageBox::warning(this, "登录失败", "用户名或密码无效。");
    } else {
        QStringList parts = receivedData.split('|');
        if (parts.size() < 2) {
            QMessageBox::critical(this, "解析错误", "服务器响应格式不正确。");
            return;
        }

        bool ok;
        int userId = parts[0].toInt(&ok);
        if (!ok) {
            QMessageBox::critical(this, "解析错误", "无法从服务器响应中解析用户ID。");
            return;
        }

        currentUserID = userId;
        currentUserTrueName = parts[1];
        currentUserName = parts[2]; // 假设第三个是username

        qDebug() << "Login successful:" << currentUserTrueName << ", username:" << currentUserName << ", id:" << currentUserID;

        // 【非常重要】处理完登录后，断开连接，让其他窗口接管
        disconnect(clientSocket, &QTcpSocket::readyRead, this, &loginWindow::onReadyRead);

        selectWindowPtr->show();
        this->hide();
    }
}


void loginWindow::on_createAccountButton_clicked()
{
    // 确保连接后再打开注册窗口
    if (clientSocket->state() != QAbstractSocket::ConnectedState) {
        QMessageBox::information(this, "提示", "请先等待连接服务器成功后再注册。");
        return;
    }
    createAccountWindowPtr = new CreateAccoutWindow(clientSocket);
    createAccountWindowPtr->show();
    connect(createAccountWindowPtr, &CreateAccoutWindow::back, this, &loginWindow::CreateAccountWindow_close);
    this->hide();
}

void loginWindow::CreateAccountWindow_close()
{
    if (createAccountWindowPtr) {
        createAccountWindowPtr->close();
        delete createAccountWindowPtr;
        createAccountWindowPtr = nullptr;
    }
    this->show();
}
